package com.futvan.tr;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import javax.swing.UIManager;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import java.awt.Color;
import javax.swing.JTextArea;

public class tr extends JFrame {

	private JPanel contentPane;
	private JTextField from_path;
	private JTextField to_path;
	private JTable keysTable;
	private JTextArea logbox;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					//设置风格
					//String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
					String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
					UIManager.setLookAndFeel(lookAndFeel);
					tr frame = new tr();
					frame.setVisible(true);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public tr() {
		setResizable(false);
		setTitle("\u6587\u6863\u5185\u5bb9\u6279\u91cf\u66ff\u6362\u3010\u652f\u6301\uff1awps\u3001wpt\u3001et\u3001ett\u3001doc\u3001docx\u3001xls\u3001xlsx\u3011");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		logbox = new JTextArea();

		//设置宽高
		setSize(440,400);
		//设置居中
		setLocationRelativeTo(null);

		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int screenHeight = screenSize.height;
		int screenWidth = screenSize.width;
		setBounds(screenWidth/4, screenHeight/4, 650, 700);

		//setBounds(100, 100, 650, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);
		setContentPane(contentPane);

		JLabel lblNewLabel = new JLabel("\u6587\u4EF6\u76EE\u5F55\uFF1A");
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel.setBounds(10, 10, 112, 29);
		contentPane.add(lblNewLabel);

		from_path = new JTextField();
		from_path.setEditable(false);
		from_path.setBounds(132, 7, 418, 32);

		contentPane.add(from_path);
		from_path.setColumns(10);


		JButton btnSelectFromPath = new JButton("\u9009\u62E9");
		btnSelectFromPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {


				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int option = fileChooser.showDialog(null, "选择");
				if (option == JFileChooser.APPROVE_OPTION) {
					File file = fileChooser.getSelectedFile();
					from_path.setText(file.toString());
				}


			}
		});
		btnSelectFromPath.setBounds(560, 6, 74, 33);
		contentPane.add(btnSelectFromPath);

		JLabel lblNewLabel_1 = new JLabel("\u4FDD\u5B58\u76EE\u5F55\uFF1A");
		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1.setBounds(10, 65, 112, 29);
		contentPane.add(lblNewLabel_1);

		to_path = new JTextField();
		to_path.setEditable(false);
		to_path.setBounds(132, 62, 418, 32);
		contentPane.add(to_path);
		to_path.setColumns(10);


//		from_path.setText("D:\\a");
//		to_path.setText("D:\\b");

		JButton btnSelectToPath = new JButton("\u9009\u62E9");
		btnSelectToPath.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int option = fileChooser.showDialog(null, "选择");
				if (option == JFileChooser.APPROVE_OPTION) {
					File file = fileChooser.getSelectedFile();
					to_path.setText(file.toString());
				}

			}
		});
		btnSelectToPath.setBounds(560, 61, 74, 33);
		contentPane.add(btnSelectToPath);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 111, 624, 307);
		contentPane.add(scrollPane);

		keysTable = new JTable();
		keysTable.setModel(new DefaultTableModel(
				new Object[][] {
//					{"2021", "2022"},
//					{"文档替换工具", "内容替换器"},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
					{null, null},
				},
				new String[] {
						"\u5F85\u66FF\u6362\u4FE1\u606F","\u66FF\u6362\u4FE1\u606F"
				}
				));
		keysTable.setRowHeight(30);
		keysTable.setFont(new Font("微软雅黑",0,18));
		keysTable.getColumnModel().getColumn(0).setPreferredWidth(268);
		keysTable.getColumnModel().getColumn(1).setPreferredWidth(313);
		scrollPane.setViewportView(keysTable);


		JButton btnRun = new JButton("执行替换");
		btnRun.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				//判读替换信息表格是否是编辑状态，如果果，结束编辑状态
				if (keysTable.isEditing()) {
					keysTable.getCellEditor().stopCellEditing();
				}

				//获取文件目录与保存目录
				String fp = from_path.getText();
				String tp = to_path.getText();
				if(z.isNotNull(fp)) {
					if(z.isNotNull(tp)) {
						//获取关键词
						HashMap<String,String> keys = new HashMap<String,String>();
						for (int i = 0; i < keysTable.getRowCount(); i++) {
							String oldtext = String.valueOf(keysTable.getModel().getValueAt(i, 0));
							String newtext = String.valueOf(keysTable.getModel().getValueAt(i, 1));
							if(z.isNotNull(oldtext) && z.isNotNull(newtext)) {
								keys.put(oldtext, newtext);
							}
						}
						if(keys.size()>0) {
							Thread t = new Thread(new Runnable(){  
								@Override
								public void run() {
									if(z.alertReturn("确定要开始执行替换吗？")){
										try {
											TestReplace(fp, tp, keys);
										} catch (Exception e1) {
											z.alert(z.ExceptionToString(e1));
										}
									}
								}
							});
							t.start();

						}else {
							z.alert("请输入要替换的信息");
						}
					}else {
						z.alert("请选择保存目录");
					}
				}else {
					z.alert("请选择文件目录");
				}
			}
		});
		btnRun.setBounds(541, 428, 93, 41);
		contentPane.add(btnRun);

		JButton btnClear = new JButton("清空信息");
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				from_path.setText("");
				to_path.setText("");

				for (int i = 0; i < keysTable.getRowCount(); i++) {
					keysTable.getModel().setValueAt("", i, 0);
					keysTable.getModel().setValueAt("", i, 1);
				}
			}
		});
		btnClear.setBounds(438, 428, 93, 41);
		contentPane.add(btnClear);

		JLabel lblNewLabel_2 = new JLabel("本软件发现任何错误，请联系我进行修改。微信：futvan ");
		lblNewLabel_2.setForeground(Color.BLUE);
		lblNewLabel_2.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_2.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewLabel_2.setBounds(10, 428, 418, 33);
		contentPane.add(lblNewLabel_2);

		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 481, 624, 170);
		contentPane.add(scrollPane_1);
		scrollPane_1.setViewportView(logbox);
	}



	/**
	 * 替换文件中的文本信息
	 * @param fromPath
	 * @param toPath
	 * @param keys
	 */
	public  void TestReplace(String fromPath, String toPath, HashMap<String,String> keys) throws Exception {

		//判读是否有需要替换的关键字
		if(z.isNotNull(keys) && keys.size()>0){
			//源目录
			File f = new File(fromPath);
			if(!f.exists() || !f.isDirectory()){
				z.Exception("文件目录不存在");
			}else if(f.list().length<=0){
				z.Exception("文件目录未找到文件");
			}

			//输出目录
			File t = new File(toPath);
			if(!t.exists() || !t.isDirectory()){
				//创建目录
				t.mkdirs();
			}

			//便利源目录中所有文件
			List<File> allfile = z.getPathAllFiles(f.getPath());
			pringLogToBox("开始执行文档替换");
			int n = 0;
			int en = 0;
			for (File fromfile : allfile) {
				//不读副本文件
				//新文件路径
				File tofile = new File(fromfile.getPath().replace(f.getPath(),t.getPath()));
				String extension_name = FilenameUtils.getExtension(fromfile.getName());
				try {

					if("wps".equals(extension_name) || "wpt".equals(extension_name) || "doc".equals(extension_name)){
						pringLogToBox("-------------开始替换文件："+tofile.getPath()+"----------------");
						//执行关键词替换
						int replace_count = ReplaceAndCopyDOC(fromfile,tofile,keys);
						pringLogToBox("-------------替换文件结束："+tofile.getPath()+"|替换："+replace_count+" 处");
						n++;
					}else if("docx".equals(extension_name)){
						pringLogToBox("-------------开始替换文件："+tofile.getPath()+"----------------");
						//执行关键词替换
						int replace_count = ReplaceAndCopyDOCS(fromfile,tofile,keys);
						pringLogToBox("-------------替换文件结束："+tofile.getPath()+"|替换："+replace_count+" 处");
						n++;
					}else if("xls".equals(extension_name)|| "et".equals(extension_name) || "ett".equals(extension_name)){
						pringLogToBox("-------------开始替换文件："+tofile.getPath()+"----------------");
						//执行关键词替换
						int replace_count = ReplaceAndCopyXLS(fromfile,tofile,keys);
						pringLogToBox("-------------替换文件结束：文件："+tofile.getPath()+"|替换："+replace_count+" 处");
						n++;
					}else if("xlsx".equals(extension_name)){
						pringLogToBox("-------------开始替换文件："+tofile.getPath()+"----------------");
						//执行关键词替换
						int replace_count = ReplaceAndCopyXLSX(fromfile,tofile,keys);
						pringLogToBox("-------------替换文件结束：文件："+tofile.getPath()+"|替换："+replace_count+" 处");
						n++;
					}else {
						//不能转换的，直接复制过去
						z.Exception("不支持该格式【支持的格式：wps、wpt、et、ett、doc、docx、xls、xlsx】");
					}

				} catch (Exception e) {
					FileUtils.copyFile(fromfile, tofile);
					pringLogToBox("无法执行替换文件："+tofile.getPath()+"|"+e.getMessage());
					en++;
				}

			}

			pringLogToBox("==========================================================");
			pringLogToBox("源文件夹："+fromPath);
			pringLogToBox("目标文件夹："+toPath);
			//遍历要替换的信息
			for (Map.Entry<String, String> entry : keys.entrySet()) {
				String findText = entry.getKey();
				String replaceText = entry.getValue();
				pringLogToBox("【"+findText+"】替换成【"+replaceText+"】");
			}
			pringLogToBox("文档数量："+allfile.size()+"个");
			pringLogToBox("执行成功数量："+n+"个");
			pringLogToBox("执行失败数量："+en+"个");
			pringLogToBox("==========================================================");

			boolean b = z.alertReturn("执行转换完成，是否打开保存目录？");
			if(b) {
				//打开目录
				File file=new File(toPath);
				java.awt.Desktop.getDesktop().open(file);
			}
		}else {
			pringLogToBox("替换信息不可为空");
		}
	}

	private  int ReplaceAndCopyXLSX(File fromfile, File tofile,  HashMap<String, String> keys) throws Exception {
		//源文件
		if(z.isNull(fromfile)){
			z.Exception("准备替换的文件未找到："+fromfile.getPath());
		}

		int replace_count = 0;

		FileInputStream fromFileInputStream = new FileInputStream(fromfile.getPath());

		//获取源文件
		XSSFWorkbook workbook = new XSSFWorkbook(fromFileInputStream);
		Iterator<Sheet> iterator = workbook.sheetIterator();
		while(iterator.hasNext()){
			Sheet sheet = iterator.next();
			//替换sheet名称
			String sheetname = sheet.getSheetName();
			if(z.isNotNull(sheetname)) {
				pringLogToBox("解析sheet名称："+sheetname);
				//遍历要替换的信息
				for (Map.Entry<String, String> entry : keys.entrySet()) {
					String findText = entry.getKey();
					String replaceText = entry.getValue();
					if (sheetname.contains(findText)) {
						String newString = sheetname.replace(findText, replaceText);
						workbook.setSheetName(workbook.getSheetIndex(sheetname), newString);
						pringLogToBox("========> 执行sheet名称替换：【"+findText+"】 替换成 【"+replaceText+"】");
						replace_count = replace_count + 1;
					}
				}
			}
			
			//替换表格
			for(Row row:sheet){
				for(Cell cell:row){
					if(CellType.STRING==cell.getCellType()){
						String cellString = cell.getStringCellValue();

						if(z.isNotNull(cellString)) {
							pringLogToBox("解析文档内容："+cellString);
						}
						

						//遍历要替换的信息
						for (Map.Entry<String, String> entry : keys.entrySet()) {
							String findText = entry.getKey();
							String replaceText = entry.getValue();
							if (cellString.contains(findText)) {
								String newString = cellString.replace(findText, replaceText);
								cell.setCellValue(newString);
								pringLogToBox("========> 执行替换：【"+findText+"】 替换成 【"+replaceText+"】");
								replace_count = replace_count + 1;
							}
						}
					}
				}
			}
		}

		//保存新的文件
		File toDir = new File(tofile.getParent());
		if(!toDir.exists()){
			//如果输出目录没有，自动创建
			toDir.mkdirs();
		}
		//保存新的文件
		try (FileOutputStream out = new FileOutputStream(tofile)) {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

		workbook.close();
		fromFileInputStream.close();

		return replace_count;
	}

	private  int ReplaceAndCopyXLS(File fromfile, File tofile,  HashMap<String, String> keys) throws Exception {
		//源文件
		if(z.isNull(fromfile)){
			z.Exception("准备替换的文件未找到："+fromfile.getPath());
		}

		int replace_count = 0;

		FileInputStream fromFileInputStream = new FileInputStream(fromfile.getPath());

		//获取源文件
		HSSFWorkbook workbook = new HSSFWorkbook(fromFileInputStream);
		Iterator<Sheet> iterator = workbook.sheetIterator();
		while(iterator.hasNext()){
			Sheet sheet = iterator.next();
			//替换sheet名称
			String sheetname = sheet.getSheetName();
			if(z.isNotNull(sheetname)) {
				pringLogToBox("解析sheet名称："+sheetname);
				//遍历要替换的信息
				for (Map.Entry<String, String> entry : keys.entrySet()) {
					String findText = entry.getKey();
					String replaceText = entry.getValue();
					if (sheetname.contains(findText)) {
						String newString = sheetname.replace(findText, replaceText); 
						workbook.setSheetName(workbook.getSheetIndex(sheetname), newString);
						pringLogToBox("========> 执行sheet名称替换：【"+findText+"】 替换成 【"+replaceText+"】");
						replace_count = replace_count + 1;
					}
				}
			}
			
			//替换表格
			for(Row row:sheet){
				for(Cell cell:row){
					if(CellType.STRING==cell.getCellType()){
						String cellString = cell.getStringCellValue();
						if(z.isNotNull(cellString)) {
							pringLogToBox("解析文档内容："+cellString);
						}
						//遍历要替换的信息
						for (Map.Entry<String, String> entry : keys.entrySet()) {
							String findText = entry.getKey();
							String replaceText = entry.getValue();
							if (cellString.contains(findText)) {
								String newString = cellString.replace(findText, replaceText);
								cell.setCellValue(newString);
								pringLogToBox("========> 执行替换：【"+findText+"】 替换成 【"+replaceText+"】");
								replace_count = replace_count + 1;
							}
						}
					}
				}
			}
		}

		//保存新的文件
		File toDir = new File(tofile.getParent());
		if(!toDir.exists()){
			//如果输出目录没有，自动创建
			toDir.mkdirs();
		}
		//保存新的文件
		try (FileOutputStream out = new FileOutputStream(tofile)) {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

		workbook.close();
		fromFileInputStream.close();

		return replace_count;
	}


	private  int ReplaceAndCopyDOC(File fromfile, File tofile,  HashMap<String, String> keys) throws Exception {
		//源文件
		if(z.isNull(fromfile)){
			z.Exception("准备替换的文件未找到："+fromfile.getPath());
		}

		int replace_count = 0;

		FileInputStream fromFileInputStream = new FileInputStream(fromfile.getPath());
		//获取源文件
		HWPFDocument Document = new HWPFDocument(fromFileInputStream);

		//替换页眉
		Range xwpfHeaderList = Document.getHeaderStoryRange();
		for (int i = 0; i < xwpfHeaderList.numSections(); ++i) {
			Section s = xwpfHeaderList.getSection(i);
			for (int j = 0; j < s.numParagraphs(); j++) {
				Paragraph p = s.getParagraph(j);
				for (int k = 0; k < p.numCharacterRuns(); k++) {
					CharacterRun run = p.getCharacterRun(k);
					String text = run.text();
					if(z.isNotNull(text)) {
						pringLogToBox("解析页眉文档内容："+text);
					}
					//遍历要替换的信息
					for (Map.Entry<String, String> entry : keys.entrySet()) {
						String findText = entry.getKey();
						String replaceText = entry.getValue();
						if (text.contains(findText)) {
							run.replaceText(findText, replaceText);
							pringLogToBox("========> 执行页眉替换：【"+findText+"】 替换成 【"+replaceText+"】");
							replace_count = replace_count + 1;
						}
					}

				}
			}
		}




		Range r = Document.getRange();
		for (int i = 0; i < r.numSections(); ++i) {
			Section s = r.getSection(i);
			for (int j = 0; j < s.numParagraphs(); j++) {
				Paragraph p = s.getParagraph(j);
				for (int k = 0; k < p.numCharacterRuns(); k++) {
					CharacterRun run = p.getCharacterRun(k);
					String text = run.text();
					if(z.isNotNull(text)) {
						pringLogToBox("解析文档内容："+text);
					}
					
					//遍历要替换的信息
					for (Map.Entry<String, String> entry : keys.entrySet()) {
						String findText = entry.getKey();
						String replaceText = entry.getValue();
						if (text.contains(findText)) {
							run.replaceText(findText, replaceText);
							pringLogToBox("========> 执行替换：【"+findText+"】 替换成 【"+replaceText+"】");
							replace_count = replace_count + 1;
						}
					}

				}
			}
		}

		//保存新的文件
		File toDir = new File(tofile.getParent());
		if(!toDir.exists()){
			//如果输出目录没有，自动创建
			toDir.mkdirs();
		}
		//保存新的文件
		try (FileOutputStream out = new FileOutputStream(tofile)) {
			Document.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Document.close();
		fromFileInputStream.close();

		return replace_count;
	}


	private  int ReplaceAndCopyDOCS(File fromfile, File tofile,  HashMap<String, String> keys) throws Exception {
		//源文件
		if(z.isNull(fromfile)){
			z.Exception("准备替换的文件未找到："+fromfile.getPath());
		}

		int replace_count = 0;

		FileInputStream fromFileInputStream = new FileInputStream(fromfile.getPath());

		//获取源文件
		XWPFDocument Document = new XWPFDocument(fromFileInputStream);


		//替换页眉
		List<XWPFHeader> xwpfHeaderList = Document.getHeaderList();
		for (XWPFHeader Header : xwpfHeaderList) {
			List<XWPFParagraph> xwpfParagraphList = Header.getParagraphs();
			for (XWPFParagraph paragraph : xwpfParagraphList) {
				String runtext = paragraph.getText();
				if(z.isNotNull(runtext)) {
					pringLogToBox("解析页眉文档内容："+runtext);
				}
				
				List<XWPFRun> runs = paragraph.getRuns();
				for (XWPFRun run : runs) {
					//遍历要替换的信息
					for (Map.Entry<String, String> entry : keys.entrySet()) {
						String findText = entry.getKey();
						String replaceText = entry.getValue();
						if (runtext.contains(findText)) {
							//替换段落文本
							run.setText(runtext.replace(findText,replaceText), 0);
							pringLogToBox("========> 执行页眉替换：【"+findText+"】 替换成 【"+replaceText+"】");
							replace_count = replace_count + 1;
						}
					}
				}

			}
		}



		//替换页脚
		List<XWPFFooter> XWPFFooterList = Document.getFooterList();
		for (XWPFFooter Footer : XWPFFooterList) {
			List<XWPFParagraph> xwpfParagraphList = Footer.getParagraphs();
			for (XWPFParagraph paragraph : xwpfParagraphList) {
				String runtext = paragraph.getText();
				if(z.isNotNull(runtext)) {
					pringLogToBox("解析页脚文档内容："+runtext);
				}
				
				List<XWPFRun> runs = paragraph.getRuns();
				for (XWPFRun run : runs) {
					//遍历要替换的信息
					for (Map.Entry<String, String> entry : keys.entrySet()) {
						String findText = entry.getKey();
						String replaceText = entry.getValue();
						if (runtext.contains(findText)) {
							//替换段落文本
							run.setText(runtext.replace(findText,replaceText), 0);
							pringLogToBox("========> 执行页脚替换：【"+findText+"】 替换成 【"+replaceText+"】");
							replace_count = replace_count + 1;
						}
					}
				}

			}
		}


		//替换段落只的文字
		List<XWPFParagraph> paragraphs = Document.getParagraphs();
		for (XWPFParagraph paragraph : paragraphs) {
			//判断此段落时候需要进行替换
			String text = paragraph.getText();
			List<XWPFRun> runs = paragraph.getRuns();
			//遍历所有段落
			for (XWPFRun run : runs) {
				//获取段落文本
				String runtext = run.getText(0);
				if(z.isNotNull(runtext)) {
					pringLogToBox("解析文档内容："+runtext);
				}
				
				if(z.isNotNull(runtext)){
					//遍历要替换的信息
					for (Map.Entry<String, String> entry : keys.entrySet()) {
						String findText = entry.getKey();
						String replaceText = entry.getValue();
						if (runtext.contains(findText)) {
							//替换段落文本
							run.setText(runtext.replace(findText,replaceText), 0);
							pringLogToBox("========> 执行替换：【"+findText+"】 替换成 【"+replaceText+"】");
							replace_count = replace_count + 1;
						}
					}
				}
			}
		}

		//替换表格中的文字
		List<XWPFTable> tables = Document.getTables();
		for (XWPFTable table : tables) {
			List<XWPFTableRow> rows = table.getRows();
			for (XWPFTableRow row : rows) {
				//得到表格每一行的所有表格
				List<XWPFTableCell> cells = row.getTableCells();
				for (XWPFTableCell cell : cells) {
					for (XWPFParagraph p : cell.getParagraphs()) {
						for (XWPFRun r : p.getRuns()) {
							String runtext = r.getText(0);
							//遍历要替换的信息
							for (Map.Entry<String, String> entry : keys.entrySet()) {
								String findText = entry.getKey();
								String replaceText = entry.getValue();
								if (runtext != null && runtext.contains(findText)) {
									//替换段落文本
									r.setText(runtext.replace(findText,replaceText),0);
									replace_count = replace_count + 1;
								}
							}
						}
					}
				}
			}
		}

		//保存新的文件
		File toDir = new File(tofile.getParent());
		if(!toDir.exists()){
			//如果输出目录没有，自动创建
			toDir.mkdirs();
		}
		try (FileOutputStream out = new FileOutputStream(tofile)) {
			Document.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

		Document.close();
		fromFileInputStream.close();

		return replace_count;
	}

	/**
	 * 打印日志
	 * @param info
	 */
	public synchronized void pringLogToBox(String info) {
		System.out.println(info);
		logbox.append(info+" \r\n");
		logbox.setCaretPosition(logbox.getText().length());
	}
}
